package com.atguigu.gmall.payment.service.impl;

import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.payment.mapper.PaymentInfoMapper;
import com.atguigu.gmall.payment.service.PaymentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * @author mqx
 * @date 2020-10-24 15:56:06
 */
@Service
public class PaymentServiceImpl implements PaymentService {

    @Autowired
    private PaymentInfoMapper paymentInfoMapper;

    @Autowired
    private RabbitService rabbitService;

//      在控制器层写！
//    @Autowired
//    private OrderFeignClient orderFeignClient;

    @Override
    public void savePaymentInfo(OrderInfo orderInfo, String paymentType) {
        //  在交易记录表中能否有两条一模一样的数据！ out_trade_no,order_id,payment_type 数据不能重复。
        //  可以将这两个作为联合主键；   primary key(out_trade_no,order_id,payment_type);
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderInfo.getId());
        queryWrapper.eq("payment_type", paymentType);
        queryWrapper.eq("out_trade_no", orderInfo.getOutTradeNo());
        Integer count = paymentInfoMapper.selectCount(queryWrapper);
        if(count > 0) return;


        //  创建一个paymentInfo 对象
        PaymentInfo paymentInfo = new PaymentInfo();
        //  给paymentInfo 赋值 ，数据从哪里来? serivce-order;
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setOrderId(orderInfo.getId());
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
        paymentInfo.setPaymentStatus(PaymentStatus.UNPAID.name());
        paymentInfo.setSubject(orderInfo.getTradeBody());
        //paymentInfo.setSubject("test");
        paymentInfo.setTotalAmount(orderInfo.getTotalAmount());

        paymentInfoMapper.insert(paymentInfo);
    }

    @Override
    public PaymentInfo getPaymentInfo(String outTradeNo, String name) {
        //  查询数据
        QueryWrapper<PaymentInfo> paymentInfoQueryWrapper = new QueryWrapper<>();
        paymentInfoQueryWrapper.eq("out_trade_no",outTradeNo).eq("payment_type",name);
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(paymentInfoQueryWrapper);

        return paymentInfo;
    }

    @Override
    public void paySuccess(String outTradeNo, String name, Map<String, String> paramMap) {

        //  如果交易记录状态，已经支付或者已经付款，则不需要更改了！
        PaymentInfo paymentInfoQuery = getPaymentInfo(outTradeNo, name);
        //  当paymentInfoQuery 不为空
        if (paymentInfoQuery!=null){
            if (paymentInfoQuery.getPaymentStatus().equals(PaymentStatus.PAID.name())
                    || paymentInfoQuery.getPaymentStatus().equals(PaymentStatus.ClOSED.name())){
                return;
            }
        }

        //  更新数据
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(paramMap.toString());
        paymentInfo.setPaymentStatus(PaymentStatus.PAID.name());
        paymentInfo.setTradeNo(paramMap.get("trade_no"));

        //  query
//        QueryWrapper<PaymentInfo> paymentInfoQueryWrapper = new QueryWrapper<>();
//        paymentInfoQueryWrapper.eq("out_trade_no",outTradeNo).eq("payment_type",name);
//        paymentInfoMapper.update(paymentInfo,paymentInfoQueryWrapper);
          updatePaymentInfo(outTradeNo,name,paymentInfo);

        //  更新订单 --- 减少库存。。。 此处使用mq 消息通知！
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_PAYMENT_PAY,MqConst.ROUTING_PAYMENT_PAY,paymentInfoQuery.getOrderId());


    }

    public void updatePaymentInfo(String outTradeNo, String name,PaymentInfo paymentInfo) {
        QueryWrapper<PaymentInfo> paymentInfoQueryWrapper = new QueryWrapper<>();
        paymentInfoQueryWrapper.eq("out_trade_no",outTradeNo).eq("payment_type",name);
        paymentInfoMapper.update(paymentInfo,paymentInfoQueryWrapper);
    }

    @Override
    public void closePayment(Long orderId) {
        //  此处orderId 一定不为空?    yes !   根据orderId 对应找到的paymentInfo 也一定不为空！
        //  update payment_info set payment_status = close where order_id = orderId ;
        //  设置条件
        QueryWrapper<PaymentInfo> paymentInfoQueryWrapper = new QueryWrapper<>();
        paymentInfoQueryWrapper.eq("order_id",orderId);

        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setPaymentStatus(PaymentStatus.ClOSED.name());
        paymentInfoMapper.update(paymentInfo,paymentInfoQueryWrapper);

    }
}
